package com.github.postsanf.yinian.service;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.MainActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2016/10/28.
 */

public class UpdateManager {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    //判断是否更新中
    public static String tag = "1";//未点击更新

    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private String ver;//版本号
    private String urlapk;//apk地址
    private String notes;//升级说明
    private Context mContext;
    private int len;
    private NotificationManager manager;
    private Notification notif;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    //    RemoteViews contentView;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
//                    notif.mProgress.setProgress(progress);
                    notif.contentView.setTextViewText(R.id.content_view_text1, "正在下载...  " + progress + "%");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, progress, false);
                    manager.notify(0, notif);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    notif.contentView.setTextViewText(R.id.content_view_text1, "下载完成！");
                    notif.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
                    manager.notify(0, notif);
                    tag = "2";//更新完成开始安装
                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    public UpdateManager(String ver, String url, String notes, Context context) {
        this.mContext = context;
        this.ver = ver;
        this.urlapk = url;
        this.notes = notes;
    }


    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        if (isUpdate()) {
            // 显示提示对话框
            if (tag.equals("1")) {
                showNoticeDialog();
            }
        }
    }

    public void checkUpdate2() {
        if (isUpdate()) {
            // 显示提示对话框
            if (tag.equals("1")) {
                showNoticeDialog();
            } else {
                Toast.makeText(mContext, "无更新版本！", Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(mContext, "无更新版本！", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate() {
        // 获取当前软件版本
//        int versionCode = getVersionCode(mContext);
        String VersionName = getVersionName(mContext);
        String localver[] = VersionName.split("\\.");
        String urlver[] = ver.split("\\.");
        String local = localver[0] + localver[1] + localver[2];
        String url = urlver[0] + urlver[1] + urlver[2];
        if (Integer.parseInt(url) > Integer.parseInt(local)) {
            return true;
        }
        // 版本判断
//        if (!getVersionName(mContext).equals(ver)) {
//            return true;
//        }
        return false;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    private String getVersionName(Context context) {
        String VersionName = null;
        try {
            VersionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return VersionName;
    }


    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        Builder builder = new Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage(notes);
        // 更新
        builder.setPositiveButton("立马更新", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Toast.makeText(mContext, "后台更新中,请稍后...", Toast.LENGTH_LONG).show();
                tag = "3";//开始更新
//                showDownloadDialog();
                Intent i = new Intent(mContext, DownloadService.class);
                i.putExtra("urlapk", urlapk);
                mContext.startService(i);
            }
        });
        // 稍后更新
        builder.setNegativeButton("稍后", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
//        Builder builder = new Builder(mContext);
//        builder.setTitle(R.string.soft_updating);
//        // 给下载对话框增加进度条
//        final LayoutInflater inflater = LayoutInflater.from(mContext);
//        View v = inflater.inflate(R.layout.softupdate_progress, null);
//        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
//        builder.setView(v);
//        // 取消更新
//        builder.setNegativeButton("取消更新", new OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                // 设置取消状态
//                cancelUpdate = true;
//            }
//        });
//        mDownloadDialog = builder.create();
//        mDownloadDialog.show();   //不让下载进度条显示

        //点击通知栏后打开的activity
        Intent intent = new Intent(mContext, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
        manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notif = new Notification();
        notif.icon = R.drawable.ic_launcher;
        notif.tickerText = "更新通知";
        //通知栏显示所用到的布局文件
        notif.contentView = new RemoteViews(mContext.getPackageName(), R.layout.notification_item);
        notif.contentIntent = pIntent;
        manager.notify(0, notif);
        // 下载文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    private int downloadCount = 0;

    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(urlapk);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "yinian.apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中


                    do {
                        int numread = is.read(buf);
                        count += numread;

                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        Log.i("progress", "progress===" + progress);
                        Log.i("progress", "count===" + count + numread);
                        // 更新进度
                        //为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                        if (downloadCount == 0 || progress - 5 > downloadCount) {
                            downloadCount += 5;
                            mHandler.sendEmptyMessage(DOWNLOAD);
                        }
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, "yinian.apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }
}
